/* threads.h
 * Simple wrappers for Win32 threads, mutexes, etc.
 * Steve Donovan, 1999.
 */

#include <windows.h>
#include "threads.h"

DWORD WINAPI ThreadFunction(LPVOID parm);


int KernelObject::wait()
{
 DWORD dw = WaitForSingleObject(m_handle, INFINITE);
 if (dw == WAIT_OBJECT_0) { // Mutex became signalled!
    return 1;
 }
 else throw("abandoned mutex???"); 
 return 0;
}

KernelObject::~KernelObject()
{
	if (m_own) CloseHandle(m_handle);
}

Thread::Thread(bool owner)
{
  DWORD thread_id;
  m_own = owner;
  if (m_own) {
    m_handle = CreateThread(NULL,0,ThreadFunction,
                  this,CREATE_SUSPENDED,&thread_id);
  } else
    m_handle = GetCurrentThread();
}


void  Thread::piority(Thread::Piority p)
{
  int pr;
  /*
  switch(p) {
	case Thread::Lowest: pr = THREAD_PIORITY_LOWEST; break;
 	case Thread::BelowNormal: pr = THREAD_PIORITY_BELOW_NORMAL; break;
	case Thread::Normal: pr = THREAD_PIORITY_NORMAL; break;
	case Thread::AboveNormal: pr = THREAD_PIORITY_ABOVE_NORMAL; break;
	case Thread::Highest:  pr = THREAD_PIORITY_HIGEST; break;
   }
   SetThreadPiority(m_handle,pr);
   */
}

void Thread::resume()
{
  ResumeThread(m_handle);
}

void Thread::suspend()
{
  SuspendThread(m_handle);
}

void Thread::sleep(int msec)
{
 Sleep(msec);
}

void Thread::kill()
{
}

int Thread::execute()
{
 return 1;
}

static DWORD WINAPI ThreadFunction(LPVOID parm)
{
 PThread(parm)->execute(); 
 return 1;
}

//----------------------------- Mutex ---------------------------
Mutex::Mutex(char *name)
{
  m_handle = CreateMutex(NULL,FALSE,name);
  m_own = true;
}

int Mutex::release()
{
 ReleaseMutex(m_handle);
 return 1;
}


int tick_count()
{ return GetCurrentTime(); }

int win_exec(char *prog)
{
 int res = WinExec(prog, SW_SHOW);
 if (res > 1) return 1; 
 else 0;
}

void kill_process(int retcode)
{
  ExitProcess(retcode);
}  
